var express = require('express');
var router = express.Router();
// var api = require('../api');
/* GET home page. */
//引入后端接口api
var  api = require('../api/home');
var Article =  require("../api/article")
var articleinstance = new Article();
const  UserInterface =  require("../service/user")
const ShopInterface = require("../service/shop")
var userInterface = new UserInterface();
var shopInterface = new ShopInterface();

var token = require("../api/token")
router
.get('/login', function  (req, res, next) {
	  res.render('up/login',{'title':"晨泽熙"})
})
.post('/login',api.login)
.get('/', function  (req, res, next) {
	  var api_token = req.session['api_token'];
	   if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
       		 res.renderPjax('up/home/home',{});
	    }else{
	   		res.render('up/home/index',{api_token:api_token,type:'home'})
	    }
	  
})
.get('/article',async function (req,res,next){
	const path = req.baseUrl+req.path;
	const api_token = req.session['api_token'];
	//获取总条数
	const totalCount = await articleinstance.totalCount;
	//每页的条数
	const count = await articleinstance.count;
    //获取总页数
	const totalPage = Math.ceil(totalCount/count);
    //获取当前页
	const page = parseInt(req.query['page'])>totalPage?totalPage:(parseInt(req.query['page'])||1);
    
    const nextPage =  (page+1>totalPage)?null:(page+1);
    const prevPage =  (page-1<1)?null:1;
    const data =  await articleinstance.findAll((page-1)*count);
    var  pagHtml = '<ul class="pagination pagenav">';
    if(prevPage){
	    pagHtml = pagHtml+`<li ><a aria-label="Previous" href='${path}?page=${nextPage}'><span aria-hidden="true">&laquo;</span></a></li>`;
    }
    if(totalPage<=10){
    	 var pageIndex = 0;
         while(pageIndex++<totalPage){
         	pagHtml+='<li><a href="'+path+'?page='+pageIndex+'">'+pageIndex+'</a></li>'
         }
    }
    if(nextPage){
	    pagHtml+=`<li ><a href='${path}?page=${nextPage}' aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li>`
    }
   pagHtml+='</ul>';
    const responseJson = {
          api_token:api_token,
          data:data,
          type:'article',
          link:{
          	  nextPage:path+'?page='+nextPage,
          	  prevPage:path+'?page='+prevPage,
			  currentPage:path+'?page='+page,
          	  total:totalCount
          },
          pagHtml:pagHtml
    }
    console.log(responseJson);
    if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
       		 res.renderPjax('up/article/list',responseJson);
	    }else{
	   		 res.render('up/home/index',responseJson)
	    }
    
})
.get('/addarticle',function(req,res,next){
     var api_token = req.session['api_token'];
	console.log(token.verifyToken(req.session['api_token']))
     var param = req.param;
     if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
       		 res.renderPjax('up/article/add',{});
	    }else{
	   		 res.render('up/home/index',{api_token:api_token,'data':{},type:'addarticle'})
	    }



})
.post('/addarticle',function(req,res,next){
	var body = req.body || req.query;
	var {title,bloginfo,readtimes,kinds,content,createtime,updatetime,headimg,bloggerid,author} = body;
	
	var self = token.verifyToken(req.session['api_token']);
	bloggerid = self['_id'];
    author=author?author:self['User'];
    updatetime = (new Date()).getTime();
    console.log({title,bloginfo,readtimes,kinds,content,createtime,updatetime,headimg,bloggerid,author});
 //    console.log({title,bloginfo,readtimes,kinds,content,createtime,updatetime,headimg,bloggerid,author});
	readtimes = 0;
	articleinstance.add([title,bloginfo,readtimes,kinds,content,createtime,updatetime,headimg,bloggerid,author]).then(function(data){
		res.redirect('/admin/article')
	})
	// title,bloginfo,readtimes,kinds,content,createtime,updatetime,headimg,bloggerid,author
	// var 
})
//公告
.get('/notice',function(req,res,next){
	 var api_token = req.session['api_token'];
	 if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
       		 res.renderPjax('up/notice/index',{});
	    }else{
	   		 res.render('up/home/index',{api_token:api_token,'data':{},type:'notice'})
	    }

})
//评论
.get('/comment',function(req,res,next){
	 var api_token = req.session['api_token']
	  if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
	   		 res.renderPjax('up/comment/index',{});
	    }else{
	   		 res.render('up/home/index',{api_token:api_token,'data':{},type:'comment'})
	    }
 })
//评论
.get('/category',function(req,res,next){
	 var api_token = req.session['api_token']
	  if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
	   		 res.renderPjax('up/category/index',{});
	    }else{
	   		 res.render('up/home/index',{api_token:api_token,'data':{},type:'category'})
	    }
 })
.post('/article/delete',function(req,res,next){
	var body = req.body||req.param;
	articleinstance.deleteOne(body['id']).then(function(data){
		res.json(data);
	})
})
//用户
.get('/manageuser/:page?',async function(req,res,next){
	 var api_token = req.session['api_token'];
	  const page = req.params['page'];
	  var data = await userInterface.findAll(page);
	  if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
	   		 res.renderPjax('up/user/list',{data:data});
	    }else{
	   		 res.render('up/home/index',{api_token:api_token,'data':data,type:'user'})
	    }
 })

//商品列表
.get('/shop/:page?',async function(req,res,next){
	 var api_token = req.session['api_token'];
	  const page = req.params['page'];
	  var data = await shopInterface.findAll(page);
	  if (req.headers['x-pjax']) {//如果x-pjax为true使用res.renderPjax()返回页面
	   		 res.renderPjax('up/shop/',{data:data});
	    }else{
	   		 res.render('up/home/index',{api_token:api_token,'data':data,type:'shop'})
	    }
 })
module.exports = router;
